import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_wisave/CentrePage/Energy/EnergyViewDetail.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:flutter_wisave/widgets/LineChartSamplee.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart'; // 确保导入NetworkService
import '../../Tools/ToolsLocalStorage.dart';

class EnergyView extends StatefulWidget {
  const EnergyView({super.key});

  @override
  State<EnergyView> createState() => _EnergyViewState();
}

class _EnergyViewState extends State<EnergyView> {
  final NetworkService _networkService = NetworkService();
  final ValueNotifier<String> typeNameNotifier = ValueNotifier<String>('煤气');
  final ValueNotifier<String> typeValueNotifier = ValueNotifier<String>('');
  final ValueNotifier<List<double>> typeXDataNotifier =
      ValueNotifier<List<double>>([0, 0, 0, 0, 0, 0]);
  Map<String, dynamic> dayInfoList = {};
  List<String> xTitle = [];
  List<double> xRate = [];
  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result != null && result['data'] != null) {
        setState(() {
          dayInfoList = result['data'] as Map<String, dynamic>;
          typeValueNotifier.value = dayInfoList['gasAccuTotal'].toString();
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>?> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService
          .get('/plcTimer/steelouthour/dayInfo?companyId=$deptID');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in dayInfo: $e');
      return null;
    }
  }

  Future<List<dynamic>> _fetchSteelOutHourData() async {
    final NetworkService _networkService = NetworkService();
    try {
      final response =
          await _networkService.get('/plcTimer/steelouthour/dayInfoList');
      if (response.statusCode == 200) {
        final rows = response.data['rows']; // 假设返回的数据是一个列表
        return rows;
      } else {
        print('加载钢铁出厂时间数据失败: ${response.statusCode}');
        return [];
      }
    } catch (e) {
      print('Error in _fetchSteelOutHourData: $e');
      return [];
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<dynamic>>(
      future: _fetchSteelOutHourData(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return Center(child: Text('没有数据'));
        } else {
          final steelOutHourData = snapshot.data!;
          xTitle = steelOutHourData
              .map((data) => data['tjTime'].toString())
              .toList();
          xRate = steelOutHourData
              .map((data) => double.parse(data['tjTime'].toString()))
              .toList();

          final gas = steelOutHourData
              .map((data) => double.parse(data['gasAccuTotal'].toString()))
              .toList();
          final o2 = steelOutHourData
              .map((data) => double.parse(data['o2AccuTotal'].toString()))
              .toList();
          final n2 = steelOutHourData
              .map((data) => double.parse(data['n2AccuTotal'].toString()))
              .toList();
          final air = steelOutHourData
              .map((data) => double.parse(data['airAccuTotal'].toString()))
              .toList();
          final steam = steelOutHourData
              .map((data) => double.parse(data['steamAccuTotal'].toString()))
              .toList();
          final water = steelOutHourData
              .map((data) => double.parse(data['waterAccuTotal'].toString()))
              .toList();

          typeXDataNotifier.value = gas;

          return Container(
            padding: const EdgeInsets.all(15.0),
            margin: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 8.0),
            decoration: const BoxDecoration(
              color: Colors.transparent,
            ),
            child: Column(
              children: [
                Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child: Container(
                      padding: EdgeInsets.all(16.0),
                      decoration: BoxDecoration(
                        color: AppColors.cardColor,
                        borderRadius: BorderRadius.circular(8.0),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.2),
                            blurRadius: 6.0,
                          ),
                        ],
                      ),
                      child: Row(
                        children: [
                          ValueListenableBuilder<String>(
                            valueListenable: typeNameNotifier,
                            builder: (context, typeName, child) {
                              return Row(
                                children: [
                                  GestureDetector(
                                    onTap: () {
                                      Navigator.of(context).push(
                                          TDSlidePopupRoute(
                                              modalBarrierColor:
                                                  TDTheme.of(context)
                                                      .fontGyColor2,
                                              slideTransitionFrom:
                                                  SlideTransitionFrom.bottom,
                                              builder: (context) {
                                                return TDPopupBottomDisplayPanel(
                                                  title: '选择分类',
                                                  closeClick: () {
                                                    Navigator.maybePop(context);
                                                  },
                                                  child: Container(
                                                    height: 360,
                                                    child: Column(
                                                      children: [
                                                        TDCellGroup(cells: [
                                                          TDCell(
                                                              arrow: true,
                                                              title: '煤气',
                                                              onClick: (cell) {
                                                                typeNameNotifier
                                                                        .value =
                                                                    '煤气';

                                                                /// 这里数据取值有问题---待定
                                                                typeValueNotifier
                                                                        .value =
                                                                    dayInfoList[
                                                                            'gasAccuTotal']
                                                                        .toString();
                                                                typeXDataNotifier
                                                                        .value =
                                                                    gas;
                                                                Navigator.pop(
                                                                    context);
                                                              }),
                                                          TDCell(
                                                              arrow: true,
                                                              title: '氧气',
                                                              onClick: (cell) {
                                                                typeNameNotifier
                                                                        .value =
                                                                    '氧气';
                                                                typeValueNotifier
                                                                        .value =
                                                                    dayInfoList[
                                                                            'o2AccuTotal']
                                                                        .toString();
                                                                typeXDataNotifier
                                                                    .value = o2;
                                                                Navigator.pop(
                                                                    context);
                                                              }),
                                                          TDCell(
                                                              arrow: true,
                                                              title: '氮气',
                                                              onClick: (cell) {
                                                                typeNameNotifier
                                                                        .value =
                                                                    '氮气';
                                                                typeValueNotifier
                                                                        .value =
                                                                    dayInfoList[
                                                                            'n2AccuTotal']
                                                                        .toString();
                                                                typeXDataNotifier
                                                                    .value = n2;
                                                                Navigator.pop(
                                                                    context);
                                                              }),
                                                          TDCell(
                                                              arrow: true,
                                                              title: '压缩空气',
                                                              onClick: (cell) {
                                                                typeNameNotifier
                                                                        .value =
                                                                    '压缩空气';
                                                                typeValueNotifier
                                                                        .value =
                                                                    dayInfoList[
                                                                            'airAccuTotal']
                                                                        .toString();
                                                                typeXDataNotifier
                                                                        .value =
                                                                    air;
                                                                Navigator.pop(
                                                                    context);
                                                              }),
                                                          TDCell(
                                                              arrow: true,
                                                              title: '水蒸气',
                                                              onClick: (cell) {
                                                                typeNameNotifier
                                                                        .value =
                                                                    '水蒸气';
                                                                typeValueNotifier
                                                                        .value =
                                                                    dayInfoList[
                                                                            'steamAccuTotal']
                                                                        .toString();
                                                                typeXDataNotifier
                                                                        .value =
                                                                    steam;
                                                                Navigator.pop(
                                                                    context);
                                                              }),
                                                          TDCell(
                                                              arrow: true,
                                                              title: '净环水',
                                                              onClick: (cell) {
                                                                typeNameNotifier
                                                                        .value =
                                                                    '净环水';
                                                                typeValueNotifier
                                                                        .value =
                                                                    dayInfoList[
                                                                            'waterAccuTotal']
                                                                        .toString();
                                                                typeXDataNotifier
                                                                        .value =
                                                                    water;
                                                                Navigator.pop(
                                                                    context);
                                                              }),
                                                        ])
                                                      ],
                                                    ),
                                                  ),
                                                );
                                              }));
                                    },
                                    child: Text(
                                      '$typeName',
                                      style: TextStyle(
                                          color: AppColors.textPrimary),
                                    ),
                                  ),
                                  Image.asset(
                                      'assets/images/centre/icon_down.png'),
                                ],
                              );
                            },
                          ),
                        ],
                      ),
                    )),
                Padding(
                    padding: const EdgeInsets.only(top: 10, bottom: 10),
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.all(16.0),
                      decoration: BoxDecoration(
                        color: AppColors.cardColor,
                        borderRadius: BorderRadius.circular(8.0),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.2),
                            blurRadius: 6.0,
                          ),
                        ],
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TDText("吨钢能耗",
                              font: TDTheme.of(context).fontTitleMedium,
                              textColor: AppColors.textPrimary),
                          SizedBox(height: 10),
                          Stack(
                            children: [
                              Image.asset(
                                AppColors.isDarkMode
                                    ? 'assets/images/centre/centretb2bg_b.png'
                                    : 'assets/images/centre/centretb2bg.png',
                                fit: BoxFit.cover,
                                width: double.infinity,
                              ),
                              Positioned(
                                top: 10,
                                left: 0,
                                // bottom: 10,
                                right: 0,
                                child: Column(
                                  // mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    TDText("单位(m³/t)",
                                        font: TDTheme.of(context).fontBodySmall,
                                        textColor: AppColors.textPrimary),
                                    ValueListenableBuilder<String>(
                                      valueListenable: typeValueNotifier,
                                      builder: (context, typeValue, child) {
                                        return TDText(
                                          typeValue,
                                          font: TDTheme.of(context)
                                              .fontHeadlineLarge,
                                          textColor: const Color(0xFF2AB6F7),
                                        );
                                      },
                                    )
                                  ],
                                ),
                              )
                            ],
                          )
                        ],
                      ),
                    )),
                Padding(
                    padding: const EdgeInsets.only(top: 10),
                    child: Container(
                      padding: EdgeInsets.all(16.0),
                      decoration: BoxDecoration(
                        color: AppColors.cardColor,
                        borderRadius: BorderRadius.circular(8.0),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.2),
                            blurRadius: 6.0,
                          ),
                        ],
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              TDText("能耗趋势（L）",
                                  font: TDTheme.of(context).fontTitleMedium,
                                  textColor: AppColors.textPrimary),
                              Expanded(child: SizedBox()),
                              GestureDetector(
                                onTap: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) => EnergyViewDetail(
                                        spots: typeXDataNotifier.value,
                                        xTitle: xTitle,
                                        typeName: typeNameNotifier.value,
                                        typeValue: typeValueNotifier.value,
                                      ),
                                    ),
                                  );
                                },
                                child: TDText(
                                  "查看",
                                  font: TDTheme.of(context).fontBodyMedium,
                                  textColor: Color(0xFF2AB6F7),
                                ),
                              )
                            ],
                          ),
                          SizedBox(height: 10),
                          ValueListenableBuilder<List<double>>(
                            valueListenable: typeXDataNotifier,
                            builder: (context, spots, child) {
                              return LineChartSamplee(
                                spots: spots,
                                xTitle: xTitle,
                              );
                            },
                          ),
                        ],
                      ),
                    )),
              ],
            ),
          );
        }
      },
    );
  }
}
